package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    //添加
    @Override
    public void add(Integer[] permissionIds, Integer[] menuIds, Role role) {
        //添加
        roleDao.addRole(role);
        //设置角色权限关联信息
        if (permissionIds.length > 0){
            roleDao.setRoleIdAndPermissionId(role.getId(),permissionIds);
        }
        //设置角色菜单关联信息
        if(menuIds.length > 0) {
            roleDao.setRoleIdAndMenuId(role.getId(),menuIds);
        }
    }

    //根据关键字查询角色
    @Override
    public Role selectRoleByKey(String keyword) {
        return roleDao.selectRoleByKey(keyword);
    }

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页插件进行查询
        PageHelper.startPage(currentPage,pageSize);

        //查询结果封装到page中
        Page<Role> page = roleDao.selectByCondition(queryString);
        //获取相关信息
        long total = page.getTotal();
        List<Role> result = page.getResult();

        return new PageResult(total, result);
    }

    //根据id查询角色信息,用于回显编辑弹框数据
    @Override
    public Role findById(Integer id) {
        Role role = roleDao.findById(id);
        return role;
    }

    //修改角色信息
    @Override
    public void update(Integer[] permissionIds, Integer[] menuIds, Role role) {
        //修改之前首先将关联id全部删掉
        roleDao.deleteRoleIdAndPermissionIds(role.getId());
        roleDao.deleteRoleIdAndMenuIds(role.getId());

        //修改角色信息
        roleDao.updateRole(role);

        //重新关联id
        //设置角色权限关联信息
        if (permissionIds.length > 0){
            roleDao.setRoleIdAndPermissionId(role.getId(),permissionIds);
        }
        //设置角色菜单关联信息
        if(menuIds.length > 0) {
            roleDao.setRoleIdAndMenuId(role.getId(),menuIds);
        }
    }

    //查询角色关联的用户
    @Override
    public List<User> findUserByRoleId(Integer id) {
        return roleDao.findUserByRoleId(id);
    }

    @Override
    public void deleteRoleById(Integer id) {
        //首先删除关联id
        roleDao.deleteRoleIdAndPermissionIds(id);

        roleDao.deleteRoleIdAndMenuIds(id);
        //删除角色
        roleDao.deleteRoleById(id);
    }

}
